import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/views/layout'
import NotFound from '@/views/404'
import Home from '@/views/layout/home'
import Qa from '@/views/layout/qa'
import Video from '@/views/layout/video'
import User from '@/views/layout/user'
import store from '@/store'
import Search from '@/views/search'
import SearchRes from '@/views/search/result'
import Article from '@/views/article'
import Edit from '@/views/layout/user/edit'
import Chat from '@/views/layout/user/chat'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home
      },
      {
        path: 'qa',
        component: Qa
      },
      {
        path: 'video',
        component: Video
      },
      {
        path: 'user',
        component: User
      },
      {
        path: 'chat',
        component: Chat
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/search/result',
    component: SearchRes
  },
  {
    path: '/user/edit',
    component: Edit
  },
  {
    path: '/user/chat',
    component: Chat
  },
  {
    path: '/article/:id',
    component: Article
  },
  {
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

const loginURL = ['/user', '/qa', '/user/edit', '/user/chat']
// 全局的导航守卫
// 1.判断是否有token
// 2.有token 直接放行
// 3.没有token 在判断去哪
// 3.1 /home /video 等页面直接放行
// 3.2/user 编辑资料等页面 拦截去登录2
router.beforeEach((to, from, next) => {
  const token = store.state.user.token.token
  if (token) {
    // 有token 直接跳转user页面
    next()
  } else {
    // 没有token
    if (loginURL.some((item) => item === to.path)) {
      // if成立需要登录
      // next('/login')
      // 之前的写法
      router.push('/login')

      // 现在带上回来的信息
      router.push({
        path: '/login',
        query: {
          back: to.fullPath
        }
      })
    } else {
      next()
    }
  }
})

export default router
